package org.jeecg.modules.hc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.AllArgsConstructor;
import me.zhyd.oauth.utils.UuidUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.hc.controller.dao.DisPlayMerchantInfoDao;
import org.jeecg.modules.hc.entity.*;
import org.jeecg.modules.hc.mapper.*;
import org.jeecg.modules.hc.service.IHcCompanyFoodDisplayService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 企业订餐用户菜品展示
 * @Author: jeecg-boot
 * @Date:   2023-07-11
 * @Version: V1.0
 */
@Service
@AllArgsConstructor
public class HcCompanyFoodDisplayServiceImpl extends ServiceImpl<HcCompanyFoodDisplayMapper, HcCompanyFoodDisplay> implements IHcCompanyFoodDisplayService {

    private HcCompanyMerchantInfoMapper hcCompanyMerchantInfoMapper;
    private HcCompanyFoodListMapper hcCompanyFoodListMapper;
    private HcCompanyFoodDisplayMapper hcCompanyFoodDisplayMapper;
    private HcMerchantMapper hcMerchantMapper;
    private HcCompanyFoodSpecificationsMapper hcCompanyFoodSpecificationsMapper;
    private HcCompanyDetailMapper hcCompanyDetailMapper;
    private HcCompanyMerchantSettingMapper companyMerchantSettingMapper;
    private HcCompanyFoodSpecificationsMapper specificationsMapper;
    private HcCompanyMerchantSettingMapper hcCompanyMerchantSettingMapper;


    @Override
    public List<HcMerchant> queryByCompanyId(String companyId,String detailId) {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 将当前日期格式化为指定格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedDate = currentDate.format(formatter);
        LambdaQueryWrapper<HcCompanyDetail> companyDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        companyDetailLambdaQueryWrapper.eq(HcCompanyDetail::getId,detailId);
        HcCompanyDetail hcCompanyDetail = hcCompanyDetailMapper.selectOne(companyDetailLambdaQueryWrapper);

        if (null == hcCompanyDetail){
            throw new JeecgBootException("未创建昨日菜单副本,暂无菜品展示");
        }

        String listingStoreIds = hcCompanyDetail.getListingStoreIds();
        List<String> merchantIds = Arrays.asList(listingStoreIds.split(","));
        LambdaQueryWrapper<HcCompanyMerchantInfo> companyMerchantInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        companyMerchantInfoLambdaQueryWrapper.eq(HcCompanyMerchantInfo::getCompanyId,companyId);
        //获取企业对应的商户关系
//        List<HcCompanyMerchantInfo> hcCompanyMerchantInfos = hcCompanyMerchantInfoMapper.selectList(companyMerchantInfoLambdaQueryWrapper);
        List<HcMerchant> merchants = new ArrayList<>();
        for (String merchantId : merchantIds) {
            HcMerchant hcMerchant = hcMerchantMapper.selectOne(new LambdaQueryWrapper<HcMerchant>().eq(HcMerchant::getId, merchantId));
            //判断是否需要满减
            HcCompanyMerchantSetting hcCompanyMerchantSetting = companyMerchantSettingMapper.selectOne(new LambdaQueryWrapper<HcCompanyMerchantSetting>()
                    .eq(HcCompanyMerchantSetting::getCompanyId, companyId).eq(HcCompanyMerchantSetting::getMerchantId, hcMerchant.getId()));
//            String flag = null == hcCompanyMerchantSetting ? "no":"yes";

            hcMerchant.setIsHideFullPriceProd(hcCompanyMerchantSetting == null ? "no" : hcCompanyMerchantSetting.getIsHideFullPriceProd());
            hcMerchant.setSalePrice(hcCompanyMerchantSetting == null ? new BigDecimal(0) : hcCompanyMerchantSetting.getSalePrice());
            hcMerchant.setMerchantCooperatePrice(hcCompanyMerchantSetting == null ? new BigDecimal(0) : hcCompanyMerchantSetting.getMerchantCooperatePrice());

            //获取商户对应的展示的菜品
            LambdaQueryWrapper<HcCompanyFoodDisplay> displayLambdaQueryWrapper = new LambdaQueryWrapper<>();
            displayLambdaQueryWrapper.eq(HcCompanyFoodDisplay::getCompanyDetailId,detailId)
                    .eq(HcCompanyFoodDisplay::getMerchantId,hcMerchant.getId());
            List<HcCompanyFoodDisplay> hcCompanyFoodDisplays = hcCompanyFoodDisplayMapper.selectList(displayLambdaQueryWrapper);
            List<HcCompanyFoodList> foodLists = new ArrayList<>();
            for (HcCompanyFoodDisplay hcCompanyFoodDisplay : hcCompanyFoodDisplays) {
                LambdaQueryWrapper<HcCompanyFoodList> companyFoodListLambdaQueryWrapper = new LambdaQueryWrapper<>();
                companyFoodListLambdaQueryWrapper.eq(HcCompanyFoodList::getId,hcCompanyFoodDisplay.getFoodsListId());
                HcCompanyFoodList hcCompanyFoodList = hcCompanyFoodListMapper.selectOne(companyFoodListLambdaQueryWrapper);
                //判断
//                if (flag.equalsIgnoreCase("yes")){
//                    Integer buyedNum = hcCompanyFoodList.getBuyedNum();
//                    if (buyedNum != 0){
//                        foodLists.add(hcCompanyFoodList);
//                    }
//                }else {
                    foodLists.add(hcCompanyFoodList);
//                }
            }
            //规格信息
            List<HcCompanyFoodList> newRecords = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(foodLists)){
                foodLists.forEach( r -> {
                    if (null!=r){
                        String isUseSpecifications = r.getIsUseSpecifications();
                        if (isUseSpecifications.equalsIgnoreCase("yes")){
                            LambdaQueryWrapper<HcCompanyFoodSpecifications> foodListLambdaQueryWrapper = new LambdaQueryWrapper<>();
                            foodListLambdaQueryWrapper.eq(HcCompanyFoodSpecifications::getFoodsId,r.getId());
                            List<HcCompanyFoodSpecifications> all =hcCompanyFoodSpecificationsMapper.selectList(foodListLambdaQueryWrapper);
                            List<HcCompanyFoodSpecifications> specificationsList = all.stream().filter(s -> StringUtils.isEmpty(s.getParentId())).collect(Collectors.toList());
                            List<HcCompanyFoodSpecifications> foodSpecifications = getNextFoodSpecifications(specificationsList, all);
                            r.setSpecifications(foodSpecifications);
                        }
                        newRecords.add(r);
                    }
                });
            }

            hcMerchant.setFoodLists(newRecords);
            merchants.add(hcMerchant);
        }
        return merchants;
    }

    @Override
    public List<HcMerchant> queryByCompanyIdNew(String companyId) {

//        // 获取当前日期
//        LocalDate currentDate = LocalDate.now();
//        // 将当前日期格式化为指定格式
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//        String formattedDate = currentDate.format(formatter);
//        LambdaQueryWrapper<HcCompanyDetail> companyDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        companyDetailLambdaQueryWrapper.eq(HcCompanyDetail::getMenuDisplayTime,formattedDate).eq(HcCompanyDetail::getCompanyId,companyId);

        LambdaQueryWrapper<HcCompanyDetail> companyDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        companyDetailLambdaQueryWrapper.eq(HcCompanyDetail::getCompanyId,companyId).orderByDesc(HcCompanyDetail::getCreateTime).last("limit 1");
        HcCompanyDetail hcCompanyDetail = hcCompanyDetailMapper.selectOne(companyDetailLambdaQueryWrapper);

//        if (null == hcCompanyDetail){
//            throw new JeecgBootException("未创建昨日菜单副本,暂无菜品展示");
//        }

        LambdaQueryWrapper<HcCompanyMerchantInfo> companyMerchantInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        companyMerchantInfoLambdaQueryWrapper.eq(HcCompanyMerchantInfo::getCompanyId,companyId);
        //获取企业对应的商户关系
        String listingStoreIds = hcCompanyDetail.getListingStoreIds();
        List<String> ids = Arrays.asList(listingStoreIds.split(","));
        List<HcMerchant> merchants = new ArrayList<>();
        for (String merchantId : ids) {
            HcMerchant hcMerchant = hcMerchantMapper.selectOne(new LambdaQueryWrapper<HcMerchant>().eq(HcMerchant::getId, merchantId));
            if (null != hcMerchant){
                //判断是否需要满减
                HcCompanyMerchantSetting hcCompanyMerchantSetting = companyMerchantSettingMapper.selectOne(new LambdaQueryWrapper<HcCompanyMerchantSetting>()
                        .eq(HcCompanyMerchantSetting::getCompanyId, companyId).eq(HcCompanyMerchantSetting::getMerchantId, hcMerchant.getId()));
                String flag = null == hcCompanyMerchantSetting ? "no":"yes";

                hcMerchant.setIsHideFullPriceProd(hcCompanyMerchantSetting == null ? "no" : hcCompanyMerchantSetting.getIsHideFullPriceProd());
                hcMerchant.setSalePrice(hcCompanyMerchantSetting == null ? new BigDecimal(0) : hcCompanyMerchantSetting.getSalePrice());
                hcMerchant.setMerchantCooperatePrice(hcCompanyMerchantSetting == null ? new BigDecimal(0) : hcCompanyMerchantSetting.getMerchantCooperatePrice());

                //获取商户对应的展示的菜品
                LambdaQueryWrapper<HcCompanyFoodDisplay> displayLambdaQueryWrapper = new LambdaQueryWrapper<>();
                displayLambdaQueryWrapper.eq(HcCompanyFoodDisplay::getCompanyDetailId,hcCompanyDetail.getId())
                        .eq(HcCompanyFoodDisplay::getMerchantId,hcMerchant.getId());
                List<HcCompanyFoodDisplay> hcCompanyFoodDisplays = hcCompanyFoodDisplayMapper.selectList(displayLambdaQueryWrapper);
                List<HcCompanyFoodList> foodLists = new ArrayList<>();
                for (HcCompanyFoodDisplay hcCompanyFoodDisplay : hcCompanyFoodDisplays) {
                    LambdaQueryWrapper<HcCompanyFoodList> companyFoodListLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    companyFoodListLambdaQueryWrapper.eq(HcCompanyFoodList::getId,hcCompanyFoodDisplay.getFoodsListId());
                    HcCompanyFoodList hcCompanyFoodList = hcCompanyFoodListMapper.selectOne(companyFoodListLambdaQueryWrapper);
                    if(null !=hcCompanyFoodList){
                        //判断是否满减商品
                        if (flag.equalsIgnoreCase("yes")){
                            Integer buyedNum = hcCompanyFoodList.getBuyedNum();
                            buyedNum = buyedNum == null?0:buyedNum;
                            if (buyedNum != 0){
                                foodLists.add(hcCompanyFoodList);
                            }
                        }else {
                            foodLists.add(hcCompanyFoodList);
                        }
                    }
                }
                //规格信息
                List<HcCompanyFoodList> newRecords = new ArrayList<>();
                if (CollectionUtils.isNotEmpty(foodLists)){
                    foodLists.forEach( r -> {
                        if (null!=r){
                            String isUseSpecifications = r.getIsUseSpecifications();
                            if (isUseSpecifications.equalsIgnoreCase("yes")){
                                LambdaQueryWrapper<HcCompanyFoodSpecifications> foodListLambdaQueryWrapper = new LambdaQueryWrapper<>();
                                foodListLambdaQueryWrapper.eq(HcCompanyFoodSpecifications::getFoodsId,r.getId());
                                List<HcCompanyFoodSpecifications> all =hcCompanyFoodSpecificationsMapper.selectList(foodListLambdaQueryWrapper);
                                List<HcCompanyFoodSpecifications> specificationsList = all.stream().filter(s -> StringUtils.isEmpty(s.getParentId())).collect(Collectors.toList());
                                List<HcCompanyFoodSpecifications> foodSpecifications = getNextFoodSpecifications(specificationsList, all);
                                r.setSpecifications(foodSpecifications);
                            }
                            newRecords.add(r);
                        }
                    });
                }

                hcMerchant.setFoodLists(newRecords);
                merchants.add(hcMerchant);
            }
            }

        List<HcMerchant> res = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(merchants)){
            res = merchants.stream().filter(m -> CollectionUtils.isNotEmpty(m.getFoodLists())).collect(Collectors.toList());
        }

        return res;
    }

    @Override
    public void setMerchantInfo(DisPlayMerchantInfoDao disPlayMerchantInfoDao) {
        LambdaQueryWrapper<HcCompanyFoodList> foodListLambdaQueryWrapper = new LambdaQueryWrapper<>();
        foodListLambdaQueryWrapper.eq(HcCompanyFoodList::getCompanyId,disPlayMerchantInfoDao.getCompanyId())
                .eq(HcCompanyFoodList::getMerchantId,disPlayMerchantInfoDao.getMerchantId());
        List<HcCompanyFoodList> foodLists = hcCompanyFoodListMapper.selectList(foodListLambdaQueryWrapper);
        if (CollectionUtils.isNotEmpty(foodLists)){
            foodLists.forEach(f -> {
                f.setCooperatePrice(disPlayMerchantInfoDao.getUnifyCooperatePrice());
                f.setSalePrice(disPlayMerchantInfoDao.getUnifySalePrice());
                hcCompanyFoodListMapper.updateById(f);
            });
        }
    }

    @Override
    @Transactional
    public void addDisPlayProd(HcCompanyFoodList hcCompanyFoodList) {
        String foodId = UuidUtils.getUUID();
        hcCompanyFoodList.setId(foodId);
        hcCompanyFoodList.setBuyedNum(hcCompanyFoodList.getLimitNum());
        hcCompanyFoodListMapper.insert(hcCompanyFoodList);
        //设置规格信息
        String isUseSpecifications = hcCompanyFoodList.getIsUseSpecifications();
        if (isUseSpecifications.equals("yes")){
            List<HcCompanyFoodSpecifications> specifications = hcCompanyFoodList.getSpecifications();
            if (CollectionUtils.isEmpty(specifications)){
                throw new JeecgBootException("启用规格但是未添加规格信息");
            }
            this.addNextSpecification(specifications,foodId);
        }
        //添加关系
        HcCompanyFoodDisplay companyFoodDisplay = new HcCompanyFoodDisplay();
        companyFoodDisplay.setCompanyId(hcCompanyFoodList.getCompanyId());
        companyFoodDisplay.setCompanyDetailId(hcCompanyFoodList.getCompanyDetailId());
        companyFoodDisplay.setMerchantId(hcCompanyFoodList.getMerchantId());
        companyFoodDisplay.setFoodsListId(foodId);
        hcCompanyFoodDisplayMapper.insert(companyFoodDisplay);

    }
    private void addNextSpecification(List<HcCompanyFoodSpecifications> specifications,String foodId){
        specifications.forEach( s -> {
            List<HcCompanyFoodSpecifications> nextSpecifications = s.getNextSpecifications();
            //判断是否启用规格
            if (CollectionUtils.isEmpty(nextSpecifications)){
                s.setFoodsId(foodId);
                specificationsMapper.insert(s);
            }else {
                String id = UuidUtils.getUUID();
                s.setId(id);
                s.setFoodsId(foodId);
                specificationsMapper.insert(s);
                nextSpecifications.forEach(n -> {
                    n.setParentId(id);
                });
                addNextSpecification(nextSpecifications,foodId);
            }
        });
    }

    private List<HcCompanyFoodSpecifications> getNextFoodSpecifications(List<HcCompanyFoodSpecifications> specifications, List<HcCompanyFoodSpecifications> all){
        //遍历上级规格找到对应的下级规格
        specifications.forEach(s -> {
            List<HcCompanyFoodSpecifications> specifications1 = new ArrayList<>();
            all.forEach( a -> {
                if (StringUtils.isNotBlank(a.getParentId())){
                    if (a.getParentId().equals(s.getId())){
                        specifications1.add(a);
                        String isUseSpecifications = a.getIsUseSpecifications();
                        if (isUseSpecifications.equals("yes")){
                            List<HcCompanyFoodSpecifications> specificationList = a.getNextSpecifications();
                            getNextFoodSpecifications(specificationList,all);
                        }
                    }
                }
            });
            s.setNextSpecifications(specifications1);
        });
        return specifications;
    }
}
